<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\madmin\validate;

use think\Validate;

class ClassifyValidate extends Validate
{
    protected $rule = [];
    protected $scene = [];
    private $level = [];
    public function __construct()
    {
        parent::__construct();
        $method = strtolower($this->request->method());
        $data = $this->request->$method();
        $data = $data['data'];
        foreach ($data AS $key => $value){
            $this->level[] = $key;
            if (!empty($value['children']))
                $this->isChildrenMaxLevel($value['children'],$key);
        }
        foreach ($this->level AS $key => $value) {
            $string = 'data.';
            $array = explode('.',$value);
            if (count($array) > 1) {
                foreach ($array AS $index => $item) {
                    if ($index+1 == count($array)){
                        $string .= $item . '.';
                    }else{
                        $string .= $item . '.children.';
                    }
                }
            }else{
                $string .= $array[0].'.';
            }
//            $this->rule[$string.'children'] = 'require';
            $this->rule[$string.'status'] = 'require|integer';
            $this->rule[$string.'pid'] = 'require|integer';
            $this->rule[$string.'name'] = 'require|max:32';
//            $this->scene['save'][] = $string.'children';
            $this->scene['save'][] = $string.'status';
            $this->scene['save'][] = $string.'pid';
            $this->scene['save'][] = $string.'name';
        }
    }

    /**
     * 递归处理下级数组
     * @param array $children [ "id": 64,"name": "女装","img": "","pid": 63,"status": 1,"children": []]
     * @param string $level 层级
     */
    private function isChildrenMaxLevel(array $children, string $level) : void{
        $string = $level;
        foreach ($children AS $key => $value){
            $level = $string.'.'.$key;
            $this->level[] = $level;
            if (!empty($value['children']))
                $this->isChildrenMaxLevel($value['children'],$level);
        }
    }
//    protected $message = [
//        'children.require' => '下级分类必须上传',
//        'status.require' => '状态必须上传',
//        'status.integer' => '状态错误',
//        'pid.require' => '上级必须选择',
//        'pid.integer' => '上级错误',
//        'name.require' => '分类名必填',
//        'name.max' => '分类名最多32个字符'
//    ];
}